<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Admin;
use App\AdminRole;
use Illuminate\Http\Request;

/**
 * 后台公共控制器
 */
class AdminController extends Controller
{
    // 后台ip授权
    private $_ips = array(
        '127.0.0.1','::1'
    );
    
    /**
     * ip权限认证
     */
    public function checkip()
    {
        $ip = $this->GetIP();
        if (! in_array($ip, $this->_ips)) {
            $this->err('IP未得到授权:' . $ip);
        }
        return true;
    }
    
    public function callAction($method, $parameters)
    {
        $this->beforeAction();
        return call_user_func_array([
            $this,
            $method
        ], $parameters);
    }

    public function beforeAction()
    {
//         $this->checkip(); ##测试阶段，IP授权关闭
    }

    /**
     * 用户权限认证
     */
    public function Authuser(Request $request)
    {
        $adminId = trim($request->input('admin_id', ''));
        $menuId = trim($request->input('menu_id', ''));
        $admin = Admin::find($adminId);
        if (! $admin) {
            $this->err('管理员不存在');
        }
        if ($admin->status != 1) {
            $this->err('管理员已锁定');
        }
        if ($admin->delete_status != 1) {
            $this->err('管理员不存在');
        }
        $role = AdminRole::where('id', $admin->role_id)->first();
        if (! $role) {
            $this->err('该用户无角色');
        }
        if ($role->status != 1) {
            $this->err('角色被禁用');
        }
        
        $roleids = str_replace('[', '', $role->purview);
        $roleids = str_replace(']', '', $roleids);
        $rolePurviewArr = explode(',', $roleids);
        if (in_array($menuId, $rolePurviewArr)) {
            $this->output(array(), '认证通过');
        } else {
            $this->err('角色权限不足');
        }
    }

    public function output($data = array(), $msg = '')
    {
        // header("Content-type: text/html; charset=utf-8");
        echo json_encode(array(
            'code' => 200,
            'msg' => $msg,
            'data' => $data
        ));
        exit();
    }

    public function err($msg = '')
    {
        echo json_encode(array(
            'code' => 500,
            'msg' => $msg,
            'data' => array()
        ));
        exit();
    }

    private function GetIP()
    {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && ! empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        else if (isset($_SERVER["HTTP_CLIENT_IP"]) && ! empty($_SERVER["HTTP_CLIENT_IP"]))
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        else if ($_SERVER["REMOTE_ADDR"])
            $ip = $_SERVER["REMOTE_ADDR"];
        else if (getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else
            $ip = "Unknown";
        return $ip;
    }
    
    
    public function itemsWithPage($request, $fliter, $SearchArr=array(), $orderColumn='id', $orderType='desc'){
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '10')); // 分页个数
        //         $fliter = Product_order_after_sale::where('status', '1');
        
        if ($start) {
            $fliter = $fliter->where('created_at', '>=', $start);
        }
        if ($end) {
            $fliter = $fliter->where('created_at', '<=', $end . ' 23:59:59');
        }
        foreach ($SearchArr as $coulm => $value){
            if($value){
                $fliter = $fliter->where($coulm, $value);
            }
        }
        $fliter->orderBy($orderColumn,$orderType);
        
        $columns = [
            '*'
        ];
        $data = $fliter->paginate($pagenumber, $columns, 'page', $page + 1);
        
        $itemWithOther = array();
        $items = $data->items();
        $dataItem = array();
        foreach ($items as $item) {
            if(method_exists($item,'item')){
                $dataItem[] = $item->item();
            }else{
                $dataItem[] =$item->toArray();
            }
        }
        
        $this->output(array(
            "count" => $data->total(),
            "items" => $dataItem,
            "page" => $page
        ));
    }
    
}